﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace ImageRenderControl
{

    /// <summary>
    /// 包含 Windows API 相关常量和方法的类
    /// </summary>
    internal static class NativeMethods
    {
        public const int WS_EX_LAYERED = 0x00080000;
        public const int WS_EX_TRANSPARENT = 0x00000020;
        public const int WS_EX_NOACTIVATE = 0x08000000;
        public const int WS_CHILD = 0x40000000;

        public const int WM_NCHITTEST = 0x0084;

        public const int HTCLIENT = 1;
        public const int HTTRANSPARENT = -1;
    }

    // 绘图状态枚举
    public enum DrawingState
    {
        None,
        DrawingRectangle,
        DrawingArc,
        DrawingLine,
        DrawingInterpolatedCurve
    }

    /// <summary>
    /// 图形类型枚举
    /// </summary>
    public enum ShapeType
    {
        Rectangle,
        Line,
        Arc,
        InterpolatedCurve
    }

    /// <summary>
    /// 图形删除事件参数类
    /// </summary>
    public class ShapeRemovedEventArgs : EventArgs
    {
        public Shape RemovedShape { get; private set; }
        public ShapeType ShapeType { get; private set; }
        public PointF[] LastImageCoordinates { get; private set; }
        public PointF[] LastOverlayCoordinates { get; private set; }
        public int ShapeId { get; private set; }  // 可选：如果您为图形分配了ID

        public ShapeRemovedEventArgs(Shape shape, ShapeType type, PointF[] imageCoords, PointF[] overlayCoords, int shapeId = -1)
        {
            RemovedShape = shape;
            ShapeType = type;
            LastImageCoordinates = imageCoords;
            LastOverlayCoordinates = overlayCoords;
            ShapeId = shapeId;
        }
    }



    // 层叠窗口：无边框、透明、点击穿透的顶级窗口
    public class LayeredOverlayForm : Form
    {

        private VisionDisplayControl m_visionDisplay;
        // 常量定义
        private const float HANDLE_HIT_SIZE = 8f;
        private const float MIN_SIZE = 10f;

        // 图形集合和状态
        private readonly List<Shape> shapes = new List<Shape>();
        private Shape selectedShape = null;
        private Point lastMousePos;
        private bool isResizing = false;

        // 调整大小时的状态信息
        private RectangleShape.ResizeHandle activeRectHandle;
        private ArcShape.HandleType activeArcHandle;
        private LineShape.HandleType? activeLineHandle;
        private RectangleF originalRect;
        private PointF originalMouseDownLocal;

        // 绘图状态相关变量
        private DrawingState currentDrawingState = DrawingState.None;
        private Point drawStartPoint;
        private Shape tempDrawingShape = null; // 临时绘制形状
        private List<PointF> curveControlPoints = new List<PointF>(); // 储存曲线控制点

        // 为了处理点击穿透，需要禁用鼠标事件
        private bool mouseEventsEnabled = true;

        /// <summary>
        /// 在类的开头添加图形删除事件声明
        /// </summary>
        public event EventHandler<ShapeRemovedEventArgs> ShapeRemoved;


        public LayeredOverlayForm(VisionDisplayControl visionDisplayControl)
        {
            InitializeForm();
            m_visionDisplay = visionDisplayControl;
        }

        private void InitializeForm()
        {
            // 基本窗口设置
            FormBorderStyle = FormBorderStyle.None;
            ShowInTaskbar = false;
            TopMost = false;
            StartPosition = FormStartPosition.Manual;

            // 透明设置
            AllowTransparency = true;
            BackColor = Color.Fuchsia; // 使用一个不常用的颜色作为透明色
            TransparencyKey = Color.Fuchsia;
            Opacity = 1.0;

            // 优化绘图性能
            DoubleBuffered = true;
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                    ControlStyles.UserPaint |
                    ControlStyles.OptimizedDoubleBuffer, true);

            // 注册键盘事件
            KeyDown += LayeredOverlayForm_KeyDown;
        }

        private void LayeredOverlayForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (selectedShape == null) return;

            // 创建坐标转换函数
            Func<PointF, PointF> overlayToImageTransform = (PointF overlayPoint) =>
            {
                int imageX, imageY;
                m_visionDisplay.OverlayToImage((int)overlayPoint.X, (int)overlayPoint.Y, out imageX, out imageY);
                return new PointF(imageX, imageY);
            };

            if (e.KeyCode == Keys.R)
            {
                float delta = e.Shift ? -1f : 1f;

                if (selectedShape is RectangleShape rect)
                {
                    rect.AdjustRotation(delta, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is ArcShape arc)
                {
                    arc.AdjustRotation(delta, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is LineShape line)
                {
                    line.AdjustRotation(delta, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is InterpolatedCurveShape curve)
                {
                    curve.AdjustRotation(delta, overlayToImageTransform);
                    Invalidate();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.S)
            {
                float factor = e.Shift ? 0.98f : 1.02f;

                if (selectedShape is RectangleShape rect)
                {
                    rect.AdjustSize(factor, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is ArcShape arc)
                {
                    arc.AdjustSize(factor, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is LineShape line)
                {
                    // 临时用计算中点后向外扩展的方法
                    PointF center = line.CenterPoint;
                    PointF newStart = new PointF(
                        center.X + (line.StartPoint.X - center.X) * factor,
                        center.Y + (line.StartPoint.Y - center.Y) * factor
                    );
                    PointF newEnd = new PointF(
                        center.X + (line.EndPoint.X - center.X) * factor,
                        center.Y + (line.EndPoint.Y - center.Y) * factor
                    );
                    line.UpdateFromResizing(LineShape.HandleType.Start, newStart);
                    line.UpdateFromResizing(LineShape.HandleType.End, newEnd);
                    Invalidate();
                }
                else if (selectedShape is InterpolatedCurveShape curve)
                {
                    curve.AdjustSize(factor, overlayToImageTransform);
                    Invalidate();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.D && selectedShape is InterpolatedCurveShape curve && curve.SelectedPointIndex >= 0)
            {
                if (curve.RemoveControlPoint(curve.SelectedPointIndex))
                {
                    Invalidate();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Delete)
            {
                if (selectedShape != null)
                {
                    RemoveShape(selectedShape);
                    e.Handled = true;
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                // 按Esc取消当前绘制状态
                if (currentDrawingState != DrawingState.None)
                {
                    CancelDrawing();
                    e.Handled = true;
                }
            }
        }


        /// <summary>
        /// 触发图形删除事件的方法
        /// </summary>
        private void OnShapeRemoved(Shape shape, ShapeType type, PointF[] imageCoords, PointF[] overlayCoords, int shapeId = -1)
        {
            ShapeRemoved?.Invoke(this, new ShapeRemovedEventArgs(shape, type, imageCoords, overlayCoords, shapeId));
        }

        /// <summary>
        /// 从叠加层移除图形
        /// </summary>
        public void RemoveShape(Shape shape)
        {
            if (shape != null && shapes.Contains(shape))
            {
                // 收集图形的坐标信息，以便在事件中提供
                ShapeType shapeType = ShapeType.Rectangle;  // 默认值
                PointF[] imageCoords = null;
                PointF[] overlayCoords = null;
                int shapeId = -1;  // 默认ID，如果您的图形没有唯一ID

                // 根据图形类型获取特定数据
                if (shape is RectangleShape rectShape)
                {
                    shapeType = ShapeType.Rectangle;
                    imageCoords = rectShape.GetImageCoordinatePoints();
                    overlayCoords = rectShape.GetOverlayCoordinatePoints();
                    // 如果有ID属性：shapeId = rectShape.Id;
                }
                else if (shape is LineShape lineShape)
                {
                    shapeType = ShapeType.Line;
                    imageCoords = new PointF[] { lineShape.StartPointImage, lineShape.EndPointImage };
                    overlayCoords = new PointF[] { lineShape.StartPoint, lineShape.EndPoint };
                }
                else if (shape is ArcShape arcShape)
                {
                    shapeType = ShapeType.Arc;
                    imageCoords = new PointF[] { arcShape.StartPointImage, arcShape.MiddlePointImage, arcShape.EndPointImage };
                    overlayCoords = new PointF[] { arcShape.StartPoint, arcShape.MiddlePoint, arcShape.EndPoint };
                }
                else if (shape is InterpolatedCurveShape curveShape)
                {
                    shapeType = ShapeType.InterpolatedCurve;
                    imageCoords = curveShape.GetImageCoordinatePoints();
                    overlayCoords = curveShape.GetOverlayCoordinatePoints();
                }

                // 从集合中移除图形之前触发事件
                OnShapeRemoved(shape, shapeType, imageCoords, overlayCoords, shapeId);

                // 清除选中状态
                if (shape == selectedShape)
                    selectedShape = null;

                // 执行资源释放
                DisposeSafely(shape);

                // 从集合中移除
                shapes.Remove(shape);

                // 刷新显示
                Invalidate();
            }
        }

        /// <summary>
        /// 安全地释放图形资源
        /// </summary>
        private void DisposeSafely(Shape shape)
        {
            try
            {
                // 如果图形实现了IDisposable接口，调用Dispose方法
                if (shape is IDisposable disposable)
                {
                    disposable.Dispose();
                }

                // 如果图形持有其他需要手动清理的资源，可以在这里处理
                if (shape is RectangleShape rect)
                {
                    rect.Pen?.Dispose();  // 释放画笔资源
                }
                else if (shape is LineShape line)
                {
                    line.Pen?.Dispose();
                }
                else if (shape is ArcShape arc)
                {
                    arc.Pen?.Dispose();
                }
                else if (shape is InterpolatedCurveShape curve)
                {
                    curve.Pen?.Dispose();
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不抛出，确保删除过程继续
                Console.WriteLine($"图形资源释放错误: {ex.Message}");
            }
        }


        // 重写 WndProc 来处理点击穿透
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == NativeMethods.WM_NCHITTEST)
            {
                // 获取当前鼠标位置
                Point clientPoint = PointToClient(new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16));

                // 当处于绘制状态时始终捕获鼠标事件
                if (currentDrawingState != DrawingState.None || IsPointOnAnyShape(clientPoint))
                {
                    // 点击在图形上或正在绘制，启用鼠标事件处理
                    mouseEventsEnabled = true;
                    m.Result = (IntPtr)NativeMethods.HTCLIENT;
                    return;
                }
                else
                {
                    // 点击不在图形上，禁用鼠标事件处理并让点击穿透
                    mouseEventsEnabled = false;
                    m.Result = (IntPtr)NativeMethods.HTTRANSPARENT;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        // 使窗口支持分层和点击穿透
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                // WS_EX_LAYERED 实现分层窗口
                cp.ExStyle |= NativeMethods.WS_EX_LAYERED;
                return cp;
            }
        }

        /// <summary>
        /// 检查点是否在任何图形或控制把手上
        /// </summary>
        private bool IsPointOnAnyShape(Point point)
        {
            // 检查是否点击在调整大小的把手上
            if (selectedShape != null)
            {
                // 检查点击是否在调整大小的控制把手上
                if (selectedShape is RectangleShape rectShape)
                {
                    var handles = rectShape.GetHandleCenters();
                    foreach (var handle in handles.Values)
                    {
                        RectangleF handleRect = new RectangleF(
                            handle.X - HANDLE_HIT_SIZE / 2,
                            handle.Y - HANDLE_HIT_SIZE / 2,
                            HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                        if (handleRect.Contains(point))
                            return true;
                    }

                    // 检查是否点击在矩形边框上
                    if (rectShape.IsPointOnBorder(point, 5))
                        return true;
                }
                else if (selectedShape is ArcShape arcShape)
                {
                    var handles = arcShape.GetHandleCenters();
                    foreach (var handle in handles.Values)
                    {
                        RectangleF handleRect = new RectangleF(
                            handle.X - HANDLE_HIT_SIZE / 2,
                            handle.Y - HANDLE_HIT_SIZE / 2,
                            HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                        if (handleRect.Contains(point))
                            return true;
                    }

                    // 检查是否点击在圆弧上
                    if (arcShape.Contains(point))
                        return true;
                }
                else if (selectedShape is LineShape lineShape)
                {
                    var handles = lineShape.GetHandleCenters();
                    foreach (var handle in handles)
                    {
                        RectangleF handleRect = new RectangleF(
                            handle.Value.X - HANDLE_HIT_SIZE / 2,
                            handle.Value.Y - HANDLE_HIT_SIZE / 2,
                            HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                        if (handleRect.Contains(point))
                            return true;
                    }

                    // 检查是否点击在线段上
                    if (lineShape.Contains(point))
                        return true;
                }
                else if (selectedShape is InterpolatedCurveShape curveShape)
                {
                    // 检查是否点击在曲线控制点上
                    var controlPoints = curveShape.GetControlPointCenters();
                    foreach (var kvp in controlPoints)
                    {
                        RectangleF handleRect = new RectangleF(
                            kvp.Value.X - HANDLE_HIT_SIZE / 2,
                            kvp.Value.Y - HANDLE_HIT_SIZE / 2,
                            HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                        if (handleRect.Contains(point))
                            return true;
                    }

                    // 检查是否点击在曲线上
                    if (curveShape.Contains(point))
                        return true;
                }
            }

            // 检查是否点击在任何其他图形上
            for (int i = shapes.Count - 1; i >= 0; i--)
            {
                if (shapes[i] is RectangleShape rectShape && rectShape.IsPointOnBorder(point, 5))
                    return true;
                else if (shapes[i] is ArcShape arcShape && arcShape.Contains(point))
                    return true;
                else if (shapes[i] is LineShape lineShape && lineShape.Contains(point))
                    return true;
                else if (shapes[i] is InterpolatedCurveShape curveShape && curveShape.Contains(point))
                    return true;
            }

            return false;
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            // 使背景完全透明
            e.Graphics.Clear(BackColor);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // 绘制所有图形
            foreach (var shape in shapes)
            {
                shape.Draw(e.Graphics);
            }

            // 绘制预览图形（如果有）
            if (previewShape != null)
            {
                previewShape.Draw(e.Graphics);
            }

            // 绘制正在创建的临时图形
            if (currentDrawingState != DrawingState.None && tempDrawingShape != null)
            {
                tempDrawingShape.Draw(e.Graphics);
            }

            // 绘制正在创建的曲线控制点
            if (currentDrawingState == DrawingState.DrawingInterpolatedCurve && curveControlPoints.Count > 0)
            {
                // 绘制控制点
                foreach (var point in curveControlPoints)
                {
                    e.Graphics.FillRectangle(Brushes.Blue,
                        point.X - 3, point.Y - 3, 6, 6);
                    e.Graphics.DrawRectangle(Pens.White,
                        point.X - 3, point.Y - 3, 6, 6);
                }

                // 绘制控制点之间的连线（虚线）
                if (curveControlPoints.Count >= 2)
                {
                    using (Pen dottedPen = new Pen(Color.Gray, 1))
                    {
                        dottedPen.DashStyle = DashStyle.Dot;
                        for (int i = 0; i < curveControlPoints.Count - 1; i++)
                        {
                            e.Graphics.DrawLine(dottedPen, curveControlPoints[i], curveControlPoints[i + 1]);
                        }
                    }

                    // 显示操作提示
                    string message = "左键：添加点 | 右键：完成曲线 | ESC：取消";
                    using (Font font = new Font("Arial", 8))
                    using (SolidBrush brush = new SolidBrush(Color.White))
                    using (SolidBrush shadowBrush = new SolidBrush(Color.Black))
                    {
                        RectangleF rect = new RectangleF(10, this.Height - 25, this.Width - 20, 20);
                        e.Graphics.DrawString(message, font, shadowBrush, new PointF(rect.X + 1, rect.Y + 1));
                        e.Graphics.DrawString(message, font, brush, rect);
                    }
                }
            }
        }

        /// <summary>
        /// 设置当前绘图状态为绘制插补曲线
        /// </summary>
        public void StartDrawingInterpolatedCurve()
        {
            ClearSelection();
            CancelDrawing();
            currentDrawingState = DrawingState.DrawingInterpolatedCurve;
            curveControlPoints.Clear();
            Cursor = Cursors.Cross;
        }

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);

            if (selectedShape is InterpolatedCurveShape curve)
            {
                // 检查是否点击在曲线上但不是控制点
                if (curve.Contains(e.Location) && curve.SelectedPointIndex == -1)
                {
                    InsertControlPointInCurve(curve, e.Location);
                    Invalidate();
                }
            }
        }

        private void InsertControlPointInCurve(InterpolatedCurveShape curve, Point location)
        {
            // 计算曲线上最接近点击位置的线段
            int bestSegment = -1;
            float minDistance = float.MaxValue;

            var controlPoints = curve.ControlPoints;
            for (int i = 0; i < controlPoints.Count - 1; i++)
            {
                float distance = DistanceToLineSegment(
                    controlPoints[i],
                    controlPoints[i + 1],
                    new PointF(location.X, location.Y));

                if (distance < minDistance)
                {
                    minDistance = distance;
                    bestSegment = i;
                }
            }

            if (bestSegment >= 0)
            {
                // 在找到的线段处插入新点
                using (Matrix inverseTransform = curve.RotationMatrix.Clone())
                {
                    inverseTransform.Invert();
                    PointF[] points = new PointF[] { new PointF(location.X, location.Y) };
                    inverseTransform.TransformPoints(points);

                    curve.InsertControlPoint(bestSegment + 1, points[0]);
                }
            }
        }

        private float DistanceToLineSegment(PointF p1, PointF p2, PointF p)
        {
            float dx = p2.X - p1.X;
            float dy = p2.Y - p1.Y;
            float length = (float)Math.Sqrt(dx * dx + dy * dy);

            if (length < 0.0001f) // 防止除以零
                return (float)Math.Sqrt(
                    (p.X - p1.X) * (p.X - p1.X) +
                    (p.Y - p1.Y) * (p.Y - p1.Y));

            float t = Math.Max(0, Math.Min(1, ((p.X - p1.X) * dx + (p.Y - p1.Y) * dy) / (length * length)));

            float projX = p1.X + t * dx;
            float projY = p1.Y + t * dy;

            return (float)Math.Sqrt((p.X - projX) * (p.X - projX) + (p.Y - projY) * (p.Y - projY));
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (!mouseEventsEnabled) return;

            lastMousePos = e.Location;

            // 处理曲线绘制
            if (currentDrawingState == DrawingState.DrawingInterpolatedCurve)
            {
                // 左键添加点
                if (e.Button == MouseButtons.Left)
                {
                    curveControlPoints.Add(new PointF(e.X, e.Y));

                    // 如果已经有两个及以上的点，显示预览曲线
                    if (curveControlPoints.Count >= 2)
                    {
                        if (tempDrawingShape != null)
                        {
                            tempDrawingShape = null;
                        }

                        tempDrawingShape = new InterpolatedCurveShape(curveControlPoints, new Pen(Color.Blue, 2));
                        tempDrawingShape.IsSelected = true;
                    }
                    Invalidate();
                    return;
                }
                // 右键完成曲线绘制
                else if (e.Button == MouseButtons.Right && curveControlPoints.Count >= 2)
                {
                    // 创建最终曲线并添加到图形列表
                    InterpolatedCurveShape curve = new InterpolatedCurveShape(curveControlPoints, new Pen(Color.Blue, 2));
                    shapes.Add(curve);

                    // 重置绘图状态
                    curveControlPoints.Clear();
                    tempDrawingShape = null;
                    currentDrawingState = DrawingState.None;
                    Cursor = Cursors.Default;
                    Invalidate();
                    return;
                }
            }

            // 如果正在绘制新图形，记录起始点
            if (currentDrawingState != DrawingState.None)
            {
                drawStartPoint = e.Location;
                switch (currentDrawingState)
                {
                    case DrawingState.DrawingRectangle:
                        tempDrawingShape = new RectangleShape(e.Location.X, e.Location.Y, 1, 1);
                        break;
                    case DrawingState.DrawingArc:
                        // 使用完整的构造函数参数，初始化为一个很小的完整圆弧（0-360度）
                        tempDrawingShape = new ArcShape(e.Location.X, e.Location.Y, 1, 1, 0, 360);
                        break;
                    case DrawingState.DrawingLine:
                        tempDrawingShape = new LineShape(
                            new PointF(e.Location.X, e.Location.Y),
                            new PointF(e.Location.X, e.Location.Y)
                        );
                        break;
                }
                // 使临时图形具有一定的视觉效果
                if (tempDrawingShape != null)
                {
                    tempDrawingShape.IsSelected = true;
                }
            }
            else
            {
                bool clickedOnHandle = false;

                // 如果有选中的图形，检查是否点击在控制把手上
                if (selectedShape != null)
                {
                    clickedOnHandle = TryHandleResizeHandleClick(e.Location);
                }

                // 如果没有点击在控制把手上，则处理图形选择
                if (!clickedOnHandle)
                {
                    HandleShapeSelection(e);
                }
            }

            base.OnMouseDown(e);
        }

        /// <summary>
        /// 处理矩形调整把手的点击
        /// </summary>
        private bool TryHandleRectangleHandleClick(RectangleShape rectShape, Point clickPoint)
        {
            var handles = rectShape.GetHandleCenters();

            // 仅处理矩形四个角的把手
            foreach (var kv in handles)
            {
                if (kv.Key != RectangleShape.ResizeHandle.TopLeft &&
                    kv.Key != RectangleShape.ResizeHandle.TopRight &&
                    kv.Key != RectangleShape.ResizeHandle.BottomLeft &&
                    kv.Key != RectangleShape.ResizeHandle.BottomRight)
                    continue;

                RectangleF hitRect = new RectangleF(
                    kv.Value.X - HANDLE_HIT_SIZE / 2,
                    kv.Value.Y - HANDLE_HIT_SIZE / 2,
                    HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                if (hitRect.Contains(clickPoint))
                {
                    isResizing = true;
                    activeRectHandle = kv.Key;
                    StoreOriginalState(rectShape, clickPoint);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 处理圆弧调整把手的点击
        /// </summary>
        private bool TryHandleArcHandleClick(ArcShape arcShape, Point clickPoint)
        {
            var handles = arcShape.GetHandleCenters();

            foreach (var kv in handles)
            {
                // 考虑圆弧的所有四个控制点: StartAngle, EndAngle, TopLeft, BottomRight
                RectangleF hitRect = new RectangleF(
                    kv.Value.X - HANDLE_HIT_SIZE / 2,
                    kv.Value.Y - HANDLE_HIT_SIZE / 2,
                    HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                if (hitRect.Contains(clickPoint))
                {
                    isResizing = true;
                    activeArcHandle = kv.Key;
                    StoreOriginalState(arcShape, clickPoint);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 处理线段调整把手的点击
        /// </summary>
        private bool TryHandleLineHandleClick(LineShape lineShape, Point clickPoint)
        {
            var handles = lineShape.GetHandleCenters();

            foreach (var handle in handles)
            {
                RectangleF hitRect = new RectangleF(
                    handle.Value.X - HANDLE_HIT_SIZE / 2,
                    handle.Value.Y - HANDLE_HIT_SIZE / 2,
                    HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                if (hitRect.Contains(clickPoint))
                {
                    isResizing = true;
                    activeLineHandle = handle.Key;
                    StoreOriginalState(lineShape, clickPoint);
                    return true;
                }
            }
            return false;
        }

        private bool TryHandleCurveHandleClick(InterpolatedCurveShape curveShape, Point clickPoint)
        {
            var controlPoints = curveShape.GetControlPointCenters();

            foreach (var kvp in controlPoints)
            {
                RectangleF hitRect = new RectangleF(
                    kvp.Value.X - HANDLE_HIT_SIZE / 2,
                    kvp.Value.Y - HANDLE_HIT_SIZE / 2,
                    HANDLE_HIT_SIZE, HANDLE_HIT_SIZE);

                if (hitRect.Contains(clickPoint))
                {
                    isResizing = true;
                    curveShape.SelectedPointIndex = kvp.Key; // 设置选中控制点索引

                    // 存储原始状态
                    lastMousePos = clickPoint;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 处理鼠标点击在调整大小把手上的情况
        /// </summary>
        private bool TryHandleResizeHandleClick(Point clickPoint)
        {
            if (selectedShape is RectangleShape rectShape)
            {
                return TryHandleRectangleHandleClick(rectShape, clickPoint);
            }
            else if (selectedShape is ArcShape arcShape)
            {
                return TryHandleArcHandleClick(arcShape, clickPoint);
            }
            else if (selectedShape is LineShape lineShape)
            {
                return TryHandleLineHandleClick(lineShape, clickPoint);
            }
            else if (selectedShape is InterpolatedCurveShape curveShape)
            {
                return TryHandleCurveHandleClick(curveShape, clickPoint);
            }
            return false;
        }

        /// <summary>
        /// 存储调整大小操作前的原始状态
        /// </summary>
        private void StoreOriginalState(Shape shape, Point clickPoint)
        {
            if (shape is RectangleShape rectShape)
            {
                originalRect = new RectangleF(rectShape.TopLeftX, rectShape.TopLeftY,
                                             rectShape.Width, rectShape.Height);

                using (Matrix inverse = rectShape.RotationMatrix.Clone())
                {
                    inverse.Invert();
                    PointF[] pts = new PointF[] { clickPoint };
                    inverse.TransformPoints(pts);
                    originalMouseDownLocal = pts[0];
                }
            }
            else if (shape is ArcShape arcShape)
            {
                originalRect = new RectangleF(arcShape.TopLeftX, arcShape.TopLeftY,
                                             arcShape.Width, arcShape.Height);

                using (Matrix inverse = arcShape.RotationMatrix.Clone())
                {
                    inverse.Invert();
                    PointF[] pts = new PointF[] { clickPoint };
                    inverse.TransformPoints(pts);
                    originalMouseDownLocal = pts[0];
                }
            }
            else if (shape is LineShape lineShape)
            {
                // 对于线段，我们不需要存储矩形，但可能需要存储原始点位置
                using (Matrix inverse = lineShape.RotationMatrix.Clone())
                {
                    inverse.Invert();
                    PointF[] pts = new PointF[] { clickPoint };
                    inverse.TransformPoints(pts);
                    originalMouseDownLocal = pts[0];
                }
            }
        }

        /// <summary>
        /// 处理图形选择
        /// </summary>
        private void HandleShapeSelection(MouseEventArgs e)
        {
            // 清除所有图形的选中状态
            foreach (var s in shapes)
            {
                s.IsSelected = false;
            }
            selectedShape = null;

            // 检测是否点击在图形上（从后向前，先检测最上层的图形）
            for (int i = shapes.Count - 1; i >= 0; i--)
            {
                Shape shape = shapes[i];
                bool isHit = false;

                if (shape is RectangleShape rect && rect.IsPointOnBorder(e.Location, 5))
                {
                    isHit = true;
                }
                else if (shape is ArcShape arc && arc.Contains(e.Location))
                {
                    isHit = true;
                }
                else if (shape is LineShape line && line.Contains(e.Location))
                {
                    isHit = true;
                }
                else if (shape is InterpolatedCurveShape curve && curve.Contains(e.Location))
                {
                    isHit = true;
                }

                if (isHit)
                {
                    selectedShape = shape;
                    selectedShape.IsSelected = true;
                    // 将选中的图形置顶
                    shapes.RemoveAt(i);
                    shapes.Add(shape);
                    break;
                }
            }
            Invalidate();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (!mouseEventsEnabled) return;

            // 创建坐标转换函数
            Func<PointF, PointF> overlayToImageTransform = (PointF overlayPoint) =>
            {
                int imageX, imageY;
                m_visionDisplay.OverlayToImage((int)overlayPoint.X, (int)overlayPoint.Y, out imageX, out imageY);
                return new PointF(imageX, imageY);
            };

            // 处理控制点拖动（调整大小）
            if (isResizing && selectedShape != null)
            {
                if (selectedShape is RectangleShape rectShape)
                {
                    ResizeRectangle(rectShape, e.Location);
                    // 更新图像坐标
                    rectShape.UpdateImageCoordinates(overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is ArcShape arcShape)
                {
                    HandleArcHandleDrag(arcShape, activeArcHandle, e.Location, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is LineShape lineShape && activeLineHandle.HasValue)
                {
                    HandleLineHandleDrag(lineShape, e.Location, overlayToImageTransform);
                    Invalidate();
                }
                else if (selectedShape is InterpolatedCurveShape curveShape && curveShape.SelectedPointIndex >= 0)
                {
                    // 处理曲线控制点拖动
                    curveShape.UpdateFromResizing(curveShape.SelectedPointIndex, e.Location, overlayToImageTransform);
                    Invalidate();
                }
            }
            // 处理临时绘制图形更新
            else if (currentDrawingState != DrawingState.None && tempDrawingShape != null && e.Button == MouseButtons.Left)
            {
                // 处理正在绘制的临时图形
                UpdateTempDrawingShape(e.Location, overlayToImageTransform);
                Invalidate();
            }
            // 处理整个图形移动
            else if (selectedShape != null && e.Button == MouseButtons.Left)
            {
                // 移动选中的图形
                int dx = e.X - lastMousePos.X;
                int dy = e.Y - lastMousePos.Y;
                selectedShape.Move(dx, dy, overlayToImageTransform);
                lastMousePos = e.Location;
                Invalidate();
            }
            // 曲线绘制模式下的预览
            else if (currentDrawingState == DrawingState.DrawingInterpolatedCurve)
            {
                // 当鼠标移动时显示十字光标
                Cursor = Cursors.Cross;

                // 如果已有至少一个点，可以显示从最后一个点到当前鼠标位置的预览线
                if (curveControlPoints.Count > 0)
                {
                    // 获取所有已添加的控制点
                    List<PointF> previewPoints = new List<PointF>(curveControlPoints);

                    // 添加当前鼠标位置作为临时预览点
                    previewPoints.Add(new PointF(e.X, e.Y));

                    // 创建或更新临时曲线预览
                    if (tempDrawingShape == null || !(tempDrawingShape is InterpolatedCurveShape))
                    {
                        tempDrawingShape = new InterpolatedCurveShape(previewPoints, overlayToImageTransform, new Pen(Color.Blue, 2));
                        tempDrawingShape.IsSelected = true;
                    }
                    else
                    {
                        ((InterpolatedCurveShape)tempDrawingShape).UpdateControlPoints(previewPoints, overlayToImageTransform);
                    }

                    Invalidate();
                }
            }
            // 鼠标悬停时的光标更新
            else
            {
                // 更新鼠标光标
                if (currentDrawingState != DrawingState.None)
                {
                    Cursor = Cursors.Cross; // 在绘图模式下使用十字光标
                }
                else if (IsPointOnAnyShape(e.Location))
                {
                    Cursor = Cursors.Hand; // 鼠标悬停在图形上时使用手形光标
                }
                else
                {
                    Cursor = Cursors.Default; // 默认光标
                }
            }

            base.OnMouseMove(e);
        }

        /// <summary>
        /// 更新临时绘制图形的尺寸和位置
        /// </summary>
        private void UpdateTempDrawingShape(Point currentPos, Func<PointF, PointF> overlayToImageTransform = null)
        {
            switch (currentDrawingState)
            {
                case DrawingState.DrawingRectangle:
                    if (tempDrawingShape is RectangleShape rect)
                    {
                        // 计算矩形的左上角和宽高
                        int left = Math.Min(drawStartPoint.X, currentPos.X);
                        int top = Math.Min(drawStartPoint.Y, currentPos.Y);
                        int width = Math.Abs(currentPos.X - drawStartPoint.X);
                        int height = Math.Abs(currentPos.Y - drawStartPoint.Y);

                        // 确保有最小尺寸
                        if (width < MIN_SIZE) width = (int)MIN_SIZE;
                        if (height < MIN_SIZE) height = (int)MIN_SIZE;

                        rect.UpdateFromResizing(left, top, width, height);

                        // 如果提供了坐标转换函数，更新图像坐标
                        if (overlayToImageTransform != null)
                        {
                            rect.UpdateImageCoordinates(overlayToImageTransform);
                        }
                    }
                    break;

                case DrawingState.DrawingArc:
                    if (tempDrawingShape is ArcShape arc)
                    {
                        // 计算矩形的左上角和宽高，强制为正方形以绘制圆形
                        int left = Math.Min(drawStartPoint.X, currentPos.X);
                        int top = Math.Min(drawStartPoint.Y, currentPos.Y);
                        int size = Math.Max(
                            Math.Abs(currentPos.X - drawStartPoint.X),
                            Math.Abs(currentPos.Y - drawStartPoint.Y)
                        );

                        // 确保有最小尺寸
                        if (size < MIN_SIZE) size = (int)MIN_SIZE;

                        // 对齐圆形到起始点
                        if (currentPos.X < drawStartPoint.X) left = drawStartPoint.X - size;
                        if (currentPos.Y < drawStartPoint.Y) top = drawStartPoint.Y - size;

                        arc.UpdateFromResizing(left, top, size, size);

                        // 如果提供了坐标转换函数，更新图像坐标
                        if (overlayToImageTransform != null)
                        {
                            arc.UpdateImageCoordinates(overlayToImageTransform);
                        }
                    }
                    break;

                case DrawingState.DrawingLine:
                    if (tempDrawingShape is LineShape line)
                    {
                        line.UpdateFromResizing(LineShape.HandleType.End, currentPos, overlayToImageTransform);
                    }
                    break;

                case DrawingState.DrawingInterpolatedCurve:
                    if (tempDrawingShape is InterpolatedCurveShape curve)
                    {
                        // 曲线的临时绘制有两种情况：
                        // 1. 用户正在添加/修改曲线控制点
                        // 2. 用户正在预览曲线（鼠标移动但未点击）

                        if (curve.SelectedPointIndex >= 0)
                        {
                            // 如果有选中的控制点，则更新它的位置
                            curve.UpdateFromResizing(curve.SelectedPointIndex, currentPos, overlayToImageTransform);
                        }
                        else if (curveControlPoints.Count > 0)
                        {
                            // 如果已有控制点但没有选中点，则可能是在预览下一个点
                            List<PointF> updatedPoints = new List<PointF>(curveControlPoints);

                            // 如果最后一个点是临时点，则更新它
                            if (updatedPoints.Count > 0)
                            {
                                updatedPoints[updatedPoints.Count - 1] = new PointF(currentPos.X, currentPos.Y);
                                curve.UpdateControlPoints(updatedPoints, overlayToImageTransform);
                            }
                        }
                    }
                    break;
            }
        }

        /// <summary>
        /// 调整矩形大小
        /// </summary>
        private void ResizeRectangle(RectangleShape rect, Point currentPos)
        {
            using (Matrix inverse = rect.RotationMatrix.Clone())
            {
                inverse.Invert();
                PointF[] pts = new PointF[] { currentPos };
                inverse.TransformPoints(pts);
                PointF currentLocal = pts[0];

                float dx = currentLocal.X - originalMouseDownLocal.X;
                float dy = currentLocal.Y - originalMouseDownLocal.Y;

                float newX = originalRect.X;
                float newY = originalRect.Y;
                float newWidth = originalRect.Width;
                float newHeight = originalRect.Height;

                // 根据不同的控制把手调整矩形
                switch (activeRectHandle)
                {
                    case RectangleShape.ResizeHandle.TopLeft:
                        newX = originalRect.X + dx;
                        newY = originalRect.Y + dy;
                        newWidth = originalRect.Width - dx;
                        newHeight = originalRect.Height - dy;
                        break;
                    case RectangleShape.ResizeHandle.TopRight:
                        newY = originalRect.Y + dy;
                        newWidth = originalRect.Width + dx;
                        newHeight = originalRect.Height - dy;
                        break;
                    case RectangleShape.ResizeHandle.BottomLeft:
                        newX = originalRect.X + dx;
                        newWidth = originalRect.Width - dx;
                        newHeight = originalRect.Height + dy;
                        break;
                    case RectangleShape.ResizeHandle.BottomRight:
                        newWidth = originalRect.Width + dx;
                        newHeight = originalRect.Height + dy;
                        break;
                }

                // 确保矩形大小不小于最小值
                if (newWidth < MIN_SIZE)
                {
                    newWidth = MIN_SIZE;
                    if (activeRectHandle == RectangleShape.ResizeHandle.TopLeft ||
                        activeRectHandle == RectangleShape.ResizeHandle.BottomLeft)
                    {
                        newX = originalRect.X + (originalRect.Width - MIN_SIZE);
                    }
                }
                if (newHeight < MIN_SIZE)
                {
                    newHeight = MIN_SIZE;
                    if (activeRectHandle == RectangleShape.ResizeHandle.TopLeft ||
                        activeRectHandle == RectangleShape.ResizeHandle.TopRight)
                    {
                        newY = originalRect.Y + (originalRect.Height - MIN_SIZE);
                    }
                }

                // 更新矩形大小
                rect.UpdateFromResizing(newX, newY, newWidth, newHeight);
            }
        }

        /// <summary>
        /// 处理圆弧角度调整
        /// </summary>
        private void HandleArcAngleAdjustment(ArcShape arc, Point mousePoint, bool isStartAngle)
        {
            // 获取圆弧中心
            PointF center = new PointF(
                arc.TopLeftX + arc.Width / 2,
                arc.TopLeftY + arc.Height / 2
            );

            // 将鼠标点转换到圆弧坐标系统
            using (Matrix inverse = arc.RotationMatrix.Clone())
            {
                inverse.Invert();
                PointF[] pts = new PointF[] { mousePoint };
                inverse.TransformPoints(pts);
                PointF transformedPoint = pts[0];

                // 计算鼠标点相对于圆弧中心的角度
                float dx = transformedPoint.X - center.X;
                float dy = transformedPoint.Y - center.Y;

                float angle = (float)Math.Atan2(dy, dx) * 180f / (float)Math.PI;
                if (angle < 0) angle += 360f;

                if (isStartAngle)
                {
                    // 调整起始角度，需要同时更新扫描角度以保持终点不变
                    float endAngle = (arc.StartAngle + arc.SweepAngle) % 360f;
                    float newSweepAngle = (endAngle - angle + 360f) % 360f;

                    // 更新圆弧参数
                    arc.StartAngle = angle;
                    arc.SweepAngle = newSweepAngle == 0 ? 360f : newSweepAngle;
                }
                else // 处理结束角度
                {
                    // 计算相对于起始角度的扫描角度
                    float newSweepAngle = (angle - arc.StartAngle + 360f) % 360f;

                    // 更新圆弧参数
                    arc.SweepAngle = newSweepAngle == 0 ? 360f : newSweepAngle;
                }
            }
        }

        // 处理圆弧控制点拖拽
        private void HandleArcHandleDrag(ArcShape arc, ArcShape.HandleType handleType, PointF newPosition, Func<PointF, PointF> overlayToImageTransform)
        {
            switch (handleType)
            {
                case ArcShape.HandleType.StartAngle:
                    // 计算圆心
                    float centerX = arc.TopLeftX + arc.Width / 2;
                    float centerY = arc.TopLeftY + arc.Height / 2;

                    // 计算相对于中心的角度
                    float newAngle = (float)(Math.Atan2(newPosition.Y - centerY, newPosition.X - centerX) * 180 / Math.PI);
                    newAngle = (newAngle + 360) % 360;

                    // 调整扫描角度
                    float oldEndAngle = arc.StartAngle + arc.SweepAngle;
                    arc.StartAngle = newAngle;
                    arc.SweepAngle = oldEndAngle - newAngle;

                    // 更新控制点
                    arc.UpdatePoints(newPosition, arc.MiddlePoint, arc.EndPoint, overlayToImageTransform);
                    break;

                case ArcShape.HandleType.EndAngle:
                    // 计算圆心
                    centerX = arc.TopLeftX + arc.Width / 2;
                    centerY = arc.TopLeftY + arc.Height / 2;

                    // 计算相对于中心的角度
                    newAngle = (float)(Math.Atan2(newPosition.Y - centerY, newPosition.X - centerX) * 180 / Math.PI);
                    newAngle = (newAngle + 360) % 360;

                    // 调整扫描角度
                    arc.SweepAngle = newAngle - arc.StartAngle;

                    // 更新控制点
                    arc.UpdatePoints(arc.StartPoint, arc.MiddlePoint, newPosition, overlayToImageTransform);
                    break;

                case ArcShape.HandleType.TopLeft:
                case ArcShape.HandleType.BottomRight:
                    // 定义最小大小常量
                    const float MIN_SIZE = 10f;

                    // 调整圆弧大小
                    float newWidth, newHeight;
                    if (handleType == ArcShape.HandleType.TopLeft)
                    {
                        newWidth = arc.TopLeftX + arc.Width - newPosition.X;
                        newHeight = arc.TopLeftY + arc.Height - newPosition.Y;

                        if (newWidth < MIN_SIZE || newHeight < MIN_SIZE)
                            return;

                        arc.TopLeftX = newPosition.X;
                        arc.TopLeftY = newPosition.Y;
                    }
                    else // BottomRight
                    {
                        newWidth = newPosition.X - arc.TopLeftX;
                        newHeight = newPosition.Y - arc.TopLeftY;
                    }

                    if (newWidth >= MIN_SIZE && newHeight >= MIN_SIZE)
                    {
                        // 按比例调整大小以保持圆形
                        float aspectRatio = arc.Width / arc.Height;
                        if (handleType == ArcShape.HandleType.TopLeft)
                        {
                            if (newWidth / newHeight > aspectRatio)
                                arc.TopLeftX = arc.TopLeftX + arc.Width - newHeight * aspectRatio;
                            else
                                arc.TopLeftY = arc.TopLeftY + arc.Height - newWidth / aspectRatio;
                        }

                        // 设置新尺寸
                        arc.Width = Math.Max(MIN_SIZE, newWidth);
                        arc.Height = Math.Max(MIN_SIZE, newHeight);

                        // 使用公共的更新控制点方法
                        arc.UpdateControlPoints(overlayToImageTransform);
                    }
                    break;
            }

            // 确保更新图像坐标
            if (overlayToImageTransform != null)
            {
                arc.UpdateImageCoordinates(overlayToImageTransform);
            }
        }

        // 处理线段控制点拖动
        private void HandleLineHandleDrag(LineShape line, PointF newPosition, Func<PointF, PointF> overlayToImageTransform)
        {
            if (activeLineHandle == LineShape.HandleType.Start)
            {
                line.UpdateFromResizing(LineShape.HandleType.Start, newPosition, overlayToImageTransform);
            }
            else if (activeLineHandle == LineShape.HandleType.End)
            {
                line.UpdateFromResizing(LineShape.HandleType.End, newPosition, overlayToImageTransform);
            }
            else if (activeLineHandle == LineShape.HandleType.Center)
            {
                line.UpdateFromResizing(LineShape.HandleType.Center, newPosition, overlayToImageTransform);
            }
        }

        /// <summary>
        /// 调整选中曲线的张力参数
        /// </summary>
        public void AdjustCurveTension(float tension)
        {
            if (selectedShape is InterpolatedCurveShape curve)
            {
                curve.Tension = tension;
                Invalidate();
            }
        }


        protected override void OnMouseUp(MouseEventArgs e)
        {
            if (!mouseEventsEnabled) return;

            if (currentDrawingState != DrawingState.None && tempDrawingShape != null)
            {
                // 检查临时图形是否有足够大小
                bool validShape = false;

                switch (currentDrawingState)
                {
                    case DrawingState.DrawingRectangle:
                        if (tempDrawingShape is RectangleShape rect)
                        {
                            validShape = rect.Width >= MIN_SIZE && rect.Height >= MIN_SIZE;
                        }
                        break;
                    case DrawingState.DrawingArc:
                        if (tempDrawingShape is ArcShape arc)
                        {
                            validShape = arc.Width >= MIN_SIZE && arc.Height >= MIN_SIZE;
                        }
                        break;
                    case DrawingState.DrawingLine:
                        if (tempDrawingShape is LineShape line)
                        {
                            // 计算线段长度
                            float length = (float)Math.Sqrt(
                                Math.Pow(line.EndPoint.X - line.StartPoint.X, 2) +
                                Math.Pow(line.EndPoint.Y - line.StartPoint.Y, 2)
                            );
                            validShape = length >= MIN_SIZE;
                        }
                        break;
                }

                if (validShape)
                {
                    // 添加临时图形到永久图形列表
                    tempDrawingShape.IsSelected = false;  // 取消选中状态
                    shapes.Add(tempDrawingShape);

                    // 为下一次绘制做准备
                    tempDrawingShape = null;

                    // 返回到非绘制状态
                    currentDrawingState = DrawingState.None;
                    Cursor = Cursors.Default;
                }
                else
                {
                    // 图形尺寸不够，丢弃
                    tempDrawingShape = null;
                }
                Invalidate();
            }
            else if (isResizing)
            {
                isResizing = false;
                activeLineHandle = null;
            }

            base.OnMouseUp(e);
        }

        #region 公开接口方法

        /// <summary>
        /// 设置当前绘图状态为绘制矩形
        /// </summary>
        public void StartDrawingRectangle()
        {
            ClearSelection();
            CancelDrawing();
            currentDrawingState = DrawingState.DrawingRectangle;
            Cursor = Cursors.Cross;
        }

        /// <summary>
        /// 设置当前绘图状态为绘制圆弧
        /// </summary>
        public void StartDrawingArc()
        {
            ClearSelection();
            CancelDrawing();
            currentDrawingState = DrawingState.DrawingArc;
            Cursor = Cursors.Cross;
        }

        /// <summary>
        /// 设置当前绘图状态为绘制直线
        /// </summary>
        public void StartDrawingLine()
        {
            ClearSelection();
            CancelDrawing();
            currentDrawingState = DrawingState.DrawingLine;
            Cursor = Cursors.Cross;
        }

        /// <summary>
        /// 取消当前绘制操作
        /// </summary>
        public void CancelDrawing()
        {
            if (tempDrawingShape != null)
            {
                tempDrawingShape = null;
            }

            curveControlPoints.Clear();  // 清理曲线控制点
            currentDrawingState = DrawingState.None;
            Cursor = Cursors.Default;
            Invalidate();
        }

        /// <summary>
        /// 添加图形到叠加层
        /// </summary>
        public void AddShape(Shape shape)
        {
            if (shape != null)
            {
                shapes.Add(shape);
                Invalidate();
            }
        }

        /// <summary>
        /// 清除所有图形
        /// </summary>
        public void ClearShapes()
        {
            selectedShape = null;
            shapes.Clear();
            Invalidate();
        }

        /// <summary>
        /// 获取图形集合的副本
        /// </summary>
        public IReadOnlyList<Shape> GetShapes()
        {
            return shapes.AsReadOnly();
        }

        /// <summary>
        /// 获取当前选中的图形
        /// </summary>
        public Shape GetSelectedShape()
        {
            return selectedShape;
        }

        /// <summary>
        /// 清除当前选中的图形状态
        /// </summary>
        public void ClearSelection()
        {
            if (selectedShape != null)
            {
                selectedShape.IsSelected = false;
                selectedShape = null;
                Invalidate(); // 重绘以更新界面显示
            }
        }

        /// <summary>
        /// 获取当前绘图状态
        /// </summary>
        public DrawingState GetDrawingState()
        {
            return currentDrawingState;
        }

        #endregion


        // 临时预览图形
        private Shape previewShape = null;
        /// <summary>
        /// 更新预览图形
        /// </summary>
        public void UpdatePreview(Shape shape)
        {
            previewShape = shape;
            Invalidate(); // 重绘窗体以显示更新的预览
        }

        /// <summary>
        /// 清除预览图形
        /// </summary>
        public void ClearPreview()
        {
            previewShape = null;
            Invalidate(); // 重绘窗体以清除预览
        }


        // 确保资源被正确释放
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 清理托管资源
                foreach (var shape in shapes)
                {
                    if (shape is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                }

                shapes.Clear();
                selectedShape = null;
            }

            base.Dispose(disposing);
        }

    }
}
